package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.Papers;
import com.gy.entity.result.Patents;
import com.gy.mapper.PapersMapper;
import com.gy.mapper.PatentsMapper;
import com.gy.query.PapersQuery;
import com.gy.query.PatentsQuery;
import com.gy.result.Result;
import com.gy.service.PatentsService;
import com.gy.service.UserService;
import com.gy.utils.AliOSSUtils;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PatentsServiceImpl extends ServiceImpl<PatentsMapper, Patents> implements PatentsService {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @Autowired
    private PatentsMapper patentsMapper;

    @Autowired
    private UploadController uploadController;
    @Autowired
    private UserService userService;

    /**
     * 根据openid查询某个人的专利信息
     * @return
     */
    @Override
    public Result<PageVO<Patents>> getPatents(PatentsQuery patentsQuery) {
        Long openId = UserHolder.getUser().getUserId();
        if (openId == null) {
            return Result.error("用户登录信息异常");
        }
        Page<Patents> page = Page.of(patentsQuery.getPageNo(), patentsQuery.getPageSize());
        // 排序条件
        if (!patentsQuery.getSortBy().isEmpty() || patentsQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(patentsQuery.getSortBy(),patentsQuery.getIsAsc()));
        } else {
            // 为空，默认按照出版时间排序
            page.addOrder(new OrderItem("id", false));
        }
        //构建查询条件
        LambdaQueryChainWrapper<Patents> queryWrapper = lambdaQuery().select()
                .eq(openId != null, Patents::getUserId, openId);
        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (patentsQuery.getStartDate() != null && patentsQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(patentsQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(patentsQuery.getEndDate());
                queryWrapper.between(Patents::getAuthorizationDate, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        //添加个人排名参数查询
        if (patentsQuery.getAuthorRank() != null) {
            queryWrapper.eq(Patents::getAuthorRank, patentsQuery.getAuthorRank());
        }
        Page<Patents> p =  queryWrapper.page(page);
        // 封装VO结果
        PageVO<Patents> vo = new PageVO<>();
        vo.setTotal(p.getTotal());
        vo.setPages(p.getPages());
        List<Patents> records = p.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        }
        //3.4拷贝
        vo.setList(records);
        //4.返回
        return Result.success(vo);

    }

    /**
     * 新增专利
     * @param patents
     * @return
     */
    @Override
    @Transactional
    public Result savePatent(Patents patents) {
        // 参数验证
        if (patents == null) {
            log.warn("传入的专利对象为空");
            return Result.error("专利对象不能为空");
        }

        try {
            // 设置用户 ID
            patents.setUserId(UserHolder.getUser().getUserId());

            // 保存专利
            boolean save = patentsMapper.savePatents(patents);
            if (!save) {
                return Result.error("新增失败");
            }

            // 增加用户专利计数
            userService.incrementUserPatentCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存专利时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }


    /**
     * 根据论文id删除专利
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result removePatentById(Long id) {
        Patents patents = getById(id);
        if (patents == null) {
            return Result.error("专利未找到");
        }

        String pdfPath = patents.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除专利失败");
        }
        userService.decrementUserPatentCount();
        return Result.success("专利删除成功");
    }

    /**
     * 更新专利信息
     * @param patents
     * @return
     */
    @Override
    public Result updatePapers(Patents patents) {
        // 参数验证
        if (patents == null) {
            return Result.error("专利信息不能为空");
        }
        if (patents.getId() == null) {
            return Result.error("专利ID不能为空");
        }

        try {
            int affectedRows = patentsMapper.updatePatents(patents);
            if (affectedRows > 0) {
                return Result.success(patents);
            } else {
                return Result.error("未找到对应的专利信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新专利信息时发生异常", e);
            return Result.error("更新专利信息失败");
        }
    }

    /**
     * 根据专利id主键查看专利
     * @param id
     * @return
     * @throws IllegalArgumentException 如果id为null
     */
    @Override
    public Patents getPatentsById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("专利ID不能为空");
        }

        Patents patents = patentsMapper.selectPatentsById(id);
        if (patents == null) {
            // 可以选择抛出异常或返回一个默认值
            throw new NoSuchElementException("未找到ID为" + id + "的专利");
        }

        return patents;
    }
    /**
     * 通过多个id，查询多个论文信息
     * @param ids
     * @return
     */
    @Override
    public Result getPatentsByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<Patents> patentsBatchIds = patentsMapper.selectPatentBatchIds(Arrays.asList(ids));
            return Result.success(patentsBatchIds);
        }
        return null;
    }


}
